package com.sharding.test.builder;

import com.sharding.test.strategy.ShardStrategy;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class ShardConfigHolder {

    private final static ShardConfigHolder instance = new ShardConfigHolder();

    public static ShardConfigHolder getInstance() {
        return ShardConfigHolder.instance;
    }

    private Map<String, ShardStrategy> strategyRegister = new HashMap<String, ShardStrategy>();

    private Set<String> ignoreSet;
    private Set<String> parseSet;

    private ShardConfigHolder() {}

    /**
     * 注册分表策略
     *
     * @param table
     * @param strategy
     */
    public void register(String table, ShardStrategy strategy) {
        strategyRegister.put(table.toLowerCase(), strategy);
    }

    /**
     * 查找对应表的分表策略
     *
     * @param tableName
     * @return
     */
    public ShardStrategy getStrategy(String tableName) {
        return strategyRegister.get(tableName.toLowerCase());
    }

    /**
     * 增加ignore id配置
     *
     * @param mapperId
     */
    public synchronized void addIgnoreId(String mapperId) {
        if (ignoreSet == null) {
            ignoreSet = new HashSet<String>();
        }
        ignoreSet.add(mapperId);
    }

    /**
     * 添加parse id配置
     *
     * @param mapperId
     */
    public synchronized void addParseId(String mapperId) {
        if (parseSet == null) {
            parseSet = new HashSet<String>();
        }
        parseSet.add(mapperId);
    }

    /**
     * 判断是否配置过parse id
     * 如果配置过parse id， 则只对parse id范围内的sql进行解析和修改
     *
     * @return
     */
    public boolean isConfigParseId() {
        return parseSet != null;
    }

    /**
     * 判断参数mapperId是否在parse id范围内
     *
     * @param mapperId
     * @return
     */
    public boolean isParseId(String mapperId) {
        return parseSet != null && parseSet.contains(mapperId);
    }

    /**
     * 判断参数mapperId是否在配置的ignore id范围内
     *
     * @param mapperId
     * @return
     */
    public boolean isIgnoredId(String mapperId) {
        return ignoreSet != null && ignoreSet.contains(mapperId);
    }
}
